<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */

import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import {
  addinventoryRoute,
  inventoryRouteList,
  delinventoryRoute,
  ForminventoryRoute,
  updateinventoryRoute,
  BookshelfOptions,
  LibraryOptions,
  groupOptions,
} from "@/api/inventory";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
import { onMounted, ref, reactive, nextTick, computed, watch } from "vue";

const userFormRef = ref(); // 用户表单
const loading = ref(false);
const ids = ref([]);
const total = ref(0);
let dialog = reactive({
  visible: false,
  title: "",
});

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const userList = ref([{}] as any);

let formData = ref({} as any);

/**
 * 查询
 */
function getUserList() {
  loading.value = true;
  inventoryRouteList(queryParams.value)
    .then((res: any) => {
      if (res.code == 200) {
        const updatedUserList = res.data.records.map((record: any) => {
          const timestamp = record.createTime; // 假设时间戳单位为秒
          const date = dayjs(timestamp);
          const formattedDate = date.format("YYYY/MM/DD HH:mm:ss"); // 使用 dayjs.format 方法转换为指定的日期时间格式

          record.createTime = formattedDate;

          return record;
        });
        userList.value = updatedUserList;
        total.value = res.data.total;
        //console.log(res.data, "data");
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
// 自定义校验函数
function validateRoutePower(rule, value, callback) {
  if (!value) {
    callback(new Error("所需电量不能为空"));
  } else {
    const numValue = Number(value);
    if (isNaN(numValue)) {
      callback(new Error("请输入有效的数字"));
    } else if (numValue < 0 || numValue > 99) {
      callback(new Error("请输入范围在0到99之间的数字"));
    } else {
      callback();
    }
  }
}
const rules = reactive({
  routeName: [
    { required: true, message: "盘点路线名称不能为空", trigger: "blur" },
  ],
  bookshelfList: [
    { required: false, message: "请选择书架", trigger: "change" },
  ],
  routePower: [
    { required: true, message: "所需电量不能为空", trigger: "blur" },
    { validator: validateRoutePower, trigger: "blur" },
  ],
  libraryId: [{ required: true, message: "请选择图书馆", trigger: "change" }],
});

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param
 */
const libraryref = ref();
const bookshelfref = ref();
const LibOptions = ref([] as any);
const Bookshelf = ref([] as any);
async function openDialog(userId?: number) {
  LibOptions.value = [];
  Bookshelf.value = [];

  formData.value.bookshelfList = [];
  formData.value.groupShelfList = [];

  if (userId) {
    dialog.title = "修改路线";
    const resss = await LibraryOptions(useStore.encryptedData);
    LibOptions.value = resss.data;
    const res = await ForminventoryRoute(userId);
    formData.value = res.data;
    // console.log(res, "ForminventoryRoute");
    const ress = await BookshelfOptions(res.data.libraryId as any);
    Bookshelf.value = ress.data;
    const ressss = await groupOptions(res.data.libraryId as any);
    group.value = ressss.data;
  } else {
    dialog.title = "新增路线";

    const res = await LibraryOptions(useStore.encryptedData);
    LibOptions.value = res.data;
    await nextTick();
    if (libraryref.value) {
      libraryref.value.clearValidate();
    }
    if (bookshelfref.value) {
      bookshelfref.value.clearValidate();
    }
    // console.log(LibOptions.value, "LibOptions图书下拉");
  }
  dialog.visible = true;
}
const group = ref([] as any);
const change = async (e: any) => {
  LibOptions.value = [];
  group.value = [];
  formData.value.bookshelfList = [];
  formData.value.groupShelfList = [];
  const ress = await BookshelfOptions(e);
  Bookshelf.value = ress.data;
  bookshelfref.value.clearValidate();
  // console.log(ress.data, "Bookshelf");

  const res = await groupOptions(e);
  group.value = res.data;
  //console.log(res.data, "groupOptions");
};
/**
 * 关闭用户弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  libraryref.value.clearValidate();
  bookshelfref.value.clearValidate();
  formData.value = {};
  formData.value.bookshelfList = [];
  formData.value.groupShelfList = [];
}

/**
 * 表单提交
 */
const handleSubmit = () => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.value.id;
      loading.value = true;
      if (userId) {
        // console.log(formData.value, "编辑");
        updateinventoryRoute(formData.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("修改成功");
              closeDialog();
              getUserList();
            } else {
              ElMessage.error(res.msg);
            }
            // console.log(res, "res");
          })
          .finally(() => (loading.value = false));
      } else {
        // console.log(formData.value, "formData.value");

        addinventoryRoute(formData.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("新增成功");
              closeDialog();
              getUserList();
            } else {
              ElMessage.error(res.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};
/**
 * 删除用户
 */
function handleDelete(id?: any) {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // console.log(Number(userIds), userIds);

    delinventoryRoute(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        getUserList();
      }
    });
  });
}

onMounted(() => {
  getUserList(); // 初始化用户列表数据
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;
  getUserList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getUserList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
// 计算属性，返回已排序的 Bookshelf 数据源
const sortedBookshelf = computed(() => {
  return Bookshelf.value.slice().sort((a, b) => {
    // 根据 label 的字符串大小比较
    return a.label.localeCompare(b.label);
  });
});

// 监听 formData.bookshelfList 的变化，对其进行排序
watch(
  () => formData.value.bookshelfList,
  (newValue) => {
    newValue.sort((a, b) => {
      const labelA =
        Bookshelf.value.find((item) => item.value === a)?.label || "";
      const labelB =
        Bookshelf.value.find((item) => item.value === b)?.label || "";
      return labelA.localeCompare(labelB);
    });
  }
);
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog()"
                  ><el-icon><Plus /></el-icon>新增</el-button
                >
                <!-- <el-button
                  type="danger"
                  :disabled="ids.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button -->
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="userList"
            :border="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="index"
              width="80"
              label="序号"
              :align="'center'"
              :index="indexMethod"
            />
            <!--  <el-table-column type="selection" width="55" align="center" /> > -->
            <el-table-column
              label="盘点路线名称"
              align="center"
              prop="routeName"
            />

            <el-table-column
              label="操作"
              fixed="right"
              width="220"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(scope.row.id)"
                  icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  icon="Delete"
                  @click="handleDelete(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 15px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryId" ref="libraryref">
          <el-select
            v-model="formData.libraryId"
            placeholder="请选择图书馆"
            @change="change"
          >
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="包含书架列表"
          prop="bookshelfList"
          ref="bookshelfref"
        >
          <el-select
            multiple
            :validate-on-rule-change="false"
            v-model="formData.bookshelfList"
            placeholder="请选择包含书架列表"
          >
            <el-option
              v-for="item in sortedBookshelf"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="包含组书架列表" prop="groupShelfList">
          <el-select
            multiple
            v-model="formData.groupShelfList"
            placeholder="请选择包含组书架列表"
          >
            <el-option
              v-for="item in group"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所需电量" prop="routePower">
          <el-input
            v-model="formData.routePower"
            placeholder="请输入所需电量"
          />
        </el-form-item>
        <el-form-item label="盘点路线名称" prop="routeName">
          <el-input
            v-model="formData.routeName"
            placeholder="请输入盘点路线名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
